<template>
  <div class="personal-info">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
    <h2>个人信息</h2>
        <p>管理您的个人资料和账户设置</p>
      </div>
    </div>

    <el-row :gutter="24">
      <!-- 左侧个人信息 -->
      <el-col :lg="16" :md="24">
        <!-- 基本信息 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button 
                type="primary" 
                size="small" 
                @click="editMode = !editMode"
              >
                <el-icon><Edit /></el-icon>
                {{ editMode ? '取消编辑' : '编辑信息' }}
              </el-button>
            </div>
          </template>

          <el-form 
            ref="userFormRef" 
            :model="userForm" 
            :rules="userRules" 
            label-width="100px"
            :disabled="!editMode"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="userForm.username" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="真实姓名" prop="realName">
                  <el-input v-model="userForm.realName" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="userForm.phone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="userForm.email" type="email" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="地址" prop="address">
              <el-input 
                v-model="userForm.address" 
                type="textarea" 
                :rows="2"
                placeholder="请输入详细地址"
              />
            </el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="注册时间">
                  <el-input v-model="userInfo.createTime" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="上次登录">
                  <el-input v-model="userInfo.lastLogin" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item v-if="editMode">
              <el-button type="primary" @click="saveUserInfo" :loading="saving">
                <el-icon><Check /></el-icon>
                保存修改
              </el-button>
              <el-button @click="cancelEdit">
                <el-icon><Close /></el-icon>
                取消
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 密码修改 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>密码管理</span>
            </div>
          </template>

          <el-form 
            ref="passwordFormRef" 
            :model="passwordForm" 
            :rules="passwordRules" 
            label-width="100px"
          >
            <el-form-item label="当前密码" prop="currentPassword">
              <el-input 
                v-model="passwordForm.currentPassword" 
                type="password" 
                show-password
                placeholder="请输入当前密码"
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password" 
                show-password
                placeholder="请输入6-20位新密码"
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                show-password
                placeholder="请再次输入新密码"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="changePassword" :loading="changingPassword">
                <el-icon><Key /></el-icon>
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 通知设置 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>邮箱通知设置</span>
            </div>
          </template>

          <div class="notification-settings">
            <div class="setting-item">
              <div class="setting-info">
                <h4>订单状态通知</h4>
                <p>当订单状态发生变化时接收通知</p>
              </div>
              <el-switch v-model="notificationSettings.orderStatus" @change="updateNotificationSettings" />
            </div>
            
            <div class="setting-item">
              <div class="setting-info">
                <h4>价格变动通知</h4>
                <p>当回收物品价格发生变化时接收通知</p>
              </div>
              <el-switch v-model="notificationSettings.priceChange" @change="updateNotificationSettings" />
            </div>
            
            <div class="setting-item">
              <div class="setting-info">
                <h4>系统消息通知</h4>
                <p>接收系统公告、活动信息等通知</p>
              </div>
              <el-switch v-model="notificationSettings.systemMessage" @change="updateNotificationSettings" />
            </div>
            
            <div class="setting-item">
              <div class="setting-info">
                <h4>邮件通知</h4>
                <p>通过邮件接收重要通知</p>
              </div>
              <el-switch v-model="notificationSettings.emailNotification" @change="updateNotificationSettings" />
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧统计和快捷操作 -->
      <el-col :lg="8" :md="24">
        <!-- 个人统计 -->
        <el-card class="stats-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>个人统计</span>
            </div>
          </template>

          <div class="personal-stats">
            <div class="stat-item">
              <div class="stat-icon orders">
                <el-icon size="24"><Document /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ personalStats.totalOrders }}</div>
                <div class="stat-label">总订单数</div>
              </div>
            </div>
            
            <div class="stat-item">
              <div class="stat-icon earnings">
                <el-icon size="24"><Money /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">¥{{ personalStats.totalEarnings }}</div>
                <div class="stat-label">累计收益</div>
              </div>
            </div>
            
            <div class="stat-item">
              <div class="stat-icon weight">
                <el-icon size="24"><Box /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ personalStats.totalWeight }}kg</div>
                <div class="stat-label">回收重量</div>
              </div>
            </div>
            
            <div class="stat-item">
              <div class="stat-icon points">
                <el-icon size="24"><Trophy /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ personalStats.ecoPoints }}</div>
                <div class="stat-label">环保积分</div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 快捷操作 -->
        <el-card class="actions-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span>快捷操作</span>
            </div>
          </template>

          <div class="quick-actions">
            <el-button 
              type="primary" 
              size="large" 
              @click="$router.push('/customer/create-order')"
              class="action-btn"
            >
              <el-icon><Plus /></el-icon>
              创建新订单
            </el-button>
            
            <el-button 
              type="success" 
              size="large" 
              @click="$router.push('/customer/browse')"
              class="action-btn"
            >
              <el-icon><Search /></el-icon>
              浏览物品
            </el-button>
            
            <el-button 
              type="info" 
              size="large" 
              @click="$router.push('/customer/orders')"
              class="action-btn"
            >
              <el-icon><List /></el-icon>
              我的订单
            </el-button>
            
            <el-button 
              type="warning" 
              size="large" 
              @click="$router.push('/customer/history')"
              class="action-btn"
            >
              <el-icon><Clock /></el-icon>
              历史记录
            </el-button>
          </div>
        </el-card>

      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import {
  Edit,
  Check,
  Close,
  Key,
  Document,
  Money,
  Box,
  Trophy,
  Plus,
  Search,
  List,
  Clock
} from '@element-plus/icons-vue'
import { usersAPI } from '@/api/users'

// 组件名称
defineOptions({
  name: 'PersonalInfo'
})

const store = useStore()
const router = useRouter()

// 响应式数据
const editMode = ref(false)
const saving = ref(false)
const changingPassword = ref(false)
const loading = ref(false)

// 表单引用
const userFormRef = ref()
const passwordFormRef = ref()

// 用户信息
const userInfo = ref({
  id: null,
  username: '',
  createTime: '',
  lastLogin: ''
})

// 用户表单数据
const userForm = reactive({
  username: '',
  realName: '',
  phone: '',
  email: '',
  address: ''
})

// 原始用户数据（用于取消编辑时恢复）
const originalUserForm = reactive({})

// 密码表单数据
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 通知设置
const notificationSettings = reactive({
  orderStatus: true,
  priceChange: false,
  systemMessage: true,
  emailNotification: true
})

// 个人统计数据
const personalStats = ref({
  totalOrders: 0,
  totalEarnings: '0.00',
  totalWeight: 0,
  ecoPoints: 0
})

// 表单验证规则
const userRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在2到10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    { min: 5, max: 100, message: '地址长度在5到100个字符', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value === passwordForm.currentPassword) {
          callback(new Error('新密码不能与当前密码相同'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  const second = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`
}

// 方法
const loadUserInfo = async () => {
  try {
    loading.value = true
    console.log('📦 加载用户信息...')
    
    const response = await usersAPI.getCurrentUser()
    console.log('📦 用户信息响应:', response)
    
    const userData = response.data || response
    
    // 更新用户信息
    userInfo.value = {
      id: userData.id,
      username: userData.username,
      createTime: formatDateTime(userData.createdAt),
      lastLogin: formatDateTime(userData.lastLoginAt || userData.updatedAt)
    }
    
    // 更新表单数据
    Object.assign(userForm, {
      username: userData.username,
      realName: userData.realName || '',
      phone: userData.phone || '',
      email: userData.email || '',
      address: userData.address || ''
    })
    
    // 保存原始数据
    Object.assign(originalUserForm, userForm)
    
    console.log('✅ 用户信息加载成功', userInfo.value)
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
  } finally {
    loading.value = false
  }
}

const loadPersonalStats = async () => {
  try {
    console.log('📊 加载统计数据...')
    
    const response = await usersAPI.getMyStats()
    console.log('📊 统计数据响应:', response)
    
    const stats = response.data || response
    
    personalStats.value = {
      totalOrders: stats.totalOrders || 0,
      totalEarnings: (stats.totalEarnings || 0).toFixed(2),
      totalWeight: (stats.totalWeight || 0).toFixed(1),
      ecoPoints: stats.ecoPoints || 0
    }
    
    console.log('✅ 统计数据加载成功', personalStats.value)
  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

const saveUserInfo = async () => {
  try {
    await userFormRef.value.validate()
    
    saving.value = true
    
    console.log('💾 保存用户信息...', userForm)
    
    // 调用真实的API更新用户信息
    const updateData = {
      realName: userForm.realName,
      phone: userForm.phone,
      email: userForm.email,
      address: userForm.address
    }
    
    await usersAPI.updateUser(userInfo.value.id, updateData)
    
    // 更新Vuex中的用户名
    if (userForm.realName) {
      store.commit('SET_USER_NAME', userForm.realName)
    }
    
    Object.assign(originalUserForm, userForm)
    editMode.value = false
    
    console.log('✅ 用户信息更新成功')
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error('更新用户信息失败:', error)
    if (error !== 'validation failed') {
      ElMessage.error(error.response?.data?.msg || '更新用户信息失败')
    }
  } finally {
    saving.value = false
  }
}

const cancelEdit = () => {
  Object.assign(userForm, originalUserForm)
  editMode.value = false
  userFormRef.value?.clearValidate()
}

const changePassword = async () => {
  try {
    await passwordFormRef.value.validate()
    
    await ElMessageBox.confirm(
      '确定要修改密码吗？修改后需要重新登录。',
      '确认修改',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    changingPassword.value = true
    
    console.log('🔑 修改密码...')
    
    // 调用真实的API修改密码
    await usersAPI.changePassword({
      currentPassword: passwordForm.currentPassword,
      newPassword: passwordForm.newPassword
    })
    
    // 重置表单
    Object.assign(passwordForm, {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    passwordFormRef.value?.resetFields()
    
    console.log('✅ 密码修改成功')
    ElMessage.success('密码修改成功，即将跳转登录页面...')
    
    // 延迟后跳转登录页面并清除登录状态
    setTimeout(() => {
      store.dispatch('logout')
      router.push('/login')
    }, 2000)
  } catch (error) {
    console.error('修改密码失败:', error)
    if (error !== 'validation failed' && error !== 'cancel') {
      const errorMsg = error.response?.data?.msg || '修改密码失败'
      ElMessage.error(errorMsg)
    }
  } finally {
    changingPassword.value = false
  }
}

const loadNotificationSettings = async () => {
  try {
    console.log('🔔 加载通知设置...')
    
    const response = await usersAPI.getNotificationSettings()
    console.log('🔔 通知设置响应:', response)
    
    const settings = response.data || response
    
    // 更新通知设置
    notificationSettings.orderStatus = settings.orderStatus !== undefined ? settings.orderStatus : true
    notificationSettings.priceChange = settings.priceChange !== undefined ? settings.priceChange : false
    notificationSettings.systemMessage = settings.systemMessage !== undefined ? settings.systemMessage : true
    notificationSettings.emailNotification = settings.emailNotification !== undefined ? settings.emailNotification : true
    
    console.log('✅ 通知设置加载成功', notificationSettings)
  } catch (error) {
    console.error('加载通知设置失败:', error)
    // 使用默认值，不显示错误消息
  }
}

const updateNotificationSettings = async () => {
  try {
    console.log('🔔 更新通知设置...', notificationSettings)
    
    await usersAPI.updateNotificationSettings({
      orderStatus: notificationSettings.orderStatus,
      priceChange: notificationSettings.priceChange,
      systemMessage: notificationSettings.systemMessage,
      emailNotification: notificationSettings.emailNotification
    })
    
    ElMessage.success('通知设置已更新')
  } catch (error) {
    console.error('更新通知设置失败:', error)
    ElMessage.error(error.response?.data?.msg || '更新通知设置失败')
  }
}

// 生命周期
onMounted(async () => {
  console.log('🚀 PersonalInfo页面加载')
  await loadUserInfo()
  await loadPersonalStats()
  await loadNotificationSettings()
})
</script>

<style scoped>
.personal-info {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
  padding: 20px 0;
}

.header-content h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.header-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.info-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.notification-settings {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-info h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.setting-info p {
  margin: 0;
  color: #666;
  font-size: 12px;
}

.stats-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.personal-stats {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.stat-icon.orders {
  background: linear-gradient(135deg, #409EFF 0%, #66B2FF 100%);
}

.stat-icon.earnings {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
}

.stat-icon.weight {
  background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
}

.stat-icon.points {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #666;
}

.actions-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.action-btn {
  width: 100%;
  height: 48px;
  font-size: 14px;
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .personal-stats {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-item {
    padding: 12px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
  }
  
  .stat-value {
    font-size: 16px;
  }
}

@media (max-width: 768px) {
  .personal-info {
    padding: 0 16px;
  }
  
  .page-header {
    padding: 16px 0;
  }
  
  .header-content h2 {
    font-size: 20px;
  }
  
  .personal-stats {
    grid-template-columns: 1fr;
  }
  
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .action-btn {
    height: 44px;
    font-size: 13px;
  }
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-weight: 500;
  color: #333;
}

.el-input__inner,
.el-textarea__inner {
  border-radius: 6px;
}

.el-button {
  border-radius: 6px;
}

/* 卡片阴影效果 */
.el-card {
  border: 1px solid #e6e6e6;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>



